package com.goldgov.code.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.goldgov.code.service.User;
import com.goldgov.code.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
//	@Autowired
//	private LogService logService;

	@PostMapping("/login")
	public String userLogin(@RequestParam("loginName") String loginName,@RequestParam("password") String password,HttpServletRequest request){
		User user = userService.getUser(loginName, password);
		request.getSession().setAttribute(User.USER_KEY_NAME, user);
		if(user != null) {
//			Log log = new Log(Log.LOG_TYPE_LOGIN);
//			log.setUser(user);
//			log.setLogContent(user.getName() + "登录");
//			logService.addLog(log);
			return "SUCCESS";
		}
		return "FAIL";
	}
	
	@GetMapping("/login")
	public String getLoginUser(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute(User.USER_KEY_NAME);
		if(user != null) {
			return user.getName();
		}
		return "<未登录>";
	}
	
	@GetMapping("/isLogin")
	public String isLogin(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute(User.USER_KEY_NAME);
		if(user != null) {
			return "true";
		}
		return "false";
	}
	
	@PostMapping("/logout")
	public String userLogout(HttpServletRequest request){
		request.getSession().removeAttribute(User.USER_KEY_NAME);
		return "SUCCESS";
	}
	
	@PutMapping("/pwd")
	public String updatePassword(@RequestParam("oldPwd") String oldPwd,@RequestParam("newPwd") String newPwd,HttpServletRequest request){
		User user = getUser(request);//验证是否登录了
		boolean isSuccess = userService.updatePassword(user.getLoginName(), oldPwd, newPwd);
		return isSuccess?"SUCCESS":"FAIL";
	}
	
	private User getUser(HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute(User.USER_KEY_NAME);
		if(user == null) {
			throw new RuntimeException("用户未登录或登录超时");
		}
		return user;
	}
}
